package com.acwing.partition12;

import java.io.*;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Queue;

/**
 * @author `RKC`
 * @date 2022/2/28 16:15
 */
public class AC1101献给阿尔吉侬的花束_bfs {

    private static final int N = 210;
    private static final int[][] dirs = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
    private static char[][] g = new char[N][N];
    private static int[][] dist = new int[N][N];
    private static Queue<int[]> q = new ArrayDeque<>(N * N);

    private static int n, m;

    private static final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    private static final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));

    public static void main(String[] args) throws IOException {
        int t = Integer.parseInt(reader.readLine());
        while (t-- > 0) {
            String[] ss = reader.readLine().split(" ");
            n = Integer.parseInt(ss[0]);
            m = Integer.parseInt(ss[1]);
            int[] start = null, end = null;
            for (int i = 0; i < n; i++) {
                String s = reader.readLine();
                for (int j = 0; j < m; j++) {
                    g[i][j] = s.charAt(j);
                    if (g[i][j] == 'S') start = new int[]{i, j};
                    else if (g[i][j] == 'E') end = new int[]{i, j};
                }
            }
            int ans = bfs(start, end);
            if (ans == -1) writer.write("oop!\n");
            else writer.write(ans + "\n");
        }
        writer.flush();
    }

    private static int bfs(int[] start, int[] end) {
        if (start[0] == end[0] && start[1] == end[1]) return 0;
        q.clear();
        for (int i = 0; i < N; i++) Arrays.fill(dist[i], 0);
        q.add(start);
        while (!q.isEmpty()) {
            int[] pair = q.poll();
            int x = pair[0], y = pair[1];
            for (int[] dir : dirs) {
                int nx = x + dir[0], ny = y + dir[1];
                if (nx < 0 || nx >= n || ny < 0 || ny >= m || g[nx][ny] == '#' || dist[nx][ny] != 0) continue;
                dist[nx][ny] = dist[x][y] + 1;
                if (nx == end[0] && ny == end[1]) return dist[nx][ny];
                q.add(new int[]{nx, ny});
            }
        }
        return -1;
    }
}
